package com.itheima.controller;

import com.itheima.pojo.Dept;
import com.itheima.pojo.Result;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 传统方式：
 *
 * @RequestMapping(value = "/users",method = RequestMethod.POST )
 * Rest风格中
 * 查询数据：@GetMapping("/users")
 * 增加数据：@PostMapping("/users")
 * 修改数据：@PutMapping("/users")
 * 删除数据：@DeleteMapping("/users")
 */
@RestController
@RequestMapping("/depts")
public class DeptController {
    @Autowired
    private DeptService deptService;

    @RequestMapping("/hello")
    public Result hello() {
        return Result.success("项目构建成功！");
    }

    /**
     * 查询部门信息
     *
     * @return
     */
    @GetMapping
    public Result listDept() {
        //1 调用Service层得到数据
        List<Dept> depts = deptService.listDept();
        //2 响应结果
        return Result.success(depts);
    }

    /**
     * 通过id删除部门
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}") // 类上面的路径+方法上的路径
    public Result deleteDept(@PathVariable Integer id) {
        //1 调用Service完成删除逻辑
        try {
            deptService.deleteDept(id);
            //2 响应结果给前端
            return Result.success();
        } catch (Exception e) {
            return Result.error("删除失败" + e.getMessage());
        }

    }

    @PostMapping
    public Result saveDept(@RequestBody Dept dept) {
        // 调用Service层完成逻辑
        deptService.saveDept(dept);

        // 响应数据给前端
        return Result.success();
    }


}
